package net.jotpot.http4flash
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	
	import mx.core.mx_internal;
	
	[Event(name="complete", type="flash.events.Event")]

	[Event(name="open", type="flash.events.Event")]
	
	[Event(name="httpResponseStatus", type="flash.events.HTTPStatusEvent")]
	
	[Event(name="httpStatus", type="flash.events.HTTPStatusEvent")]
	
	[Event(name="ioError", type="flash.events.IOErrorEvent")]
	
	[Event(name="securityError", type="flash.events.SecurityErrorEvent")]
	
	[Event(name="progress", type="flash.events.ProgressEvent")]
	
	public class HTTPURLLoader extends EventDispatcher
	{
		public  var _url:String;
		private var _port:uint = 80;
		
		private var socket:Socket;
		
		private var _request:HTTPURLRequest;
		
		public  var _httpRequest:String;
		
		private var headerComplete:Boolean = false;
		private var _header:Object;
		private var _data:String = "";
		private var _bytesLoaded:int = 0;
		private var _bytesTotal:int = 0;
		private var headerTmp:String = "";
		private var _httpVersion:Number;
		private var _httpStatusCode:int;
		private var _httpStatusText:String; 
		
		public function HTTPURLLoader(request:HTTPURLRequest = null)
		{
			//TODO: implement function
			super(null);
			
			_request = request;
			
			// create http-socket
			socket = new Socket();
			
			//subscribe to events
			socket.addEventListener( Event.CONNECT , onConnectEvent , false , 0 );				
			socket.addEventListener( Event.CLOSE , onCloseEvent , false, 0 );
			socket.addEventListener( IOErrorEvent.IO_ERROR , onIOErrorEvent , false, 0 );
			socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR , onSecurityErrorEvent , false, 0 );
			socket.addEventListener( ProgressEvent.SOCKET_DATA , onSocketDataEvent , false , 0 );
		}
			
		public function load(request:HTTPURLRequest):void{
			_request = request;
			
			if (parseURL()){
				try{
					socket.connect(_url,_port);
				} catch(e:Error){
					
				}
			} else {
				throw new Error("Invalid URL");
			}
		}
		
		protected function onConnectEvent(event:Event):void{
			
		}
		
		protected function onCloseEvent(event:Event):void{
			
		}
		
		protected function onIOErrorEvent(event:IOErrorEvent):void{
			dispatchEvent(event);
		}
		
		protected function onSecurityErrorEvent(event:SecurityErrorEvent):void{
			dispatchEvent(event);
		}
		
		protected function onSocketDataEvent(event:ProgressEvent):void{
			
		}
		
		private function parseURL():Boolean{
			return true;
		}

	}
}